// 校验手机号
function checkMobile(number) {
	const regex = /^1[0|1|2|3|4|5|6|7|8|9][0-9]{9}$/g
	return regex.test(number)
}

// 校验身份证
function checkCard(number) {
	const regex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/g
	return regex.test(number)
}

// 时间转换  年，月，日，周
var formatTime = (time, fmt) => {
	var o = {
		'M+': time.getMonth() + 1, // 月份
		'd+': time.getDate(), // 日
		'h+': time.getHours(), // 小时
		'm+': time.getMinutes(), // 分
		's+': time.getSeconds(), // 秒
		'q+': Math.floor((time.getMonth() + 3) / 3), // 季度
		'S': time.getMilliseconds() // 毫秒
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (time.getFullYear() + '').substr(4 - RegExp.$1.length))

	var week = {
		'0': '日',
		'1': '一',
		'2': '二',
		'3': '三',
		'4': '四',
		'5': '五',
		'6': '六'
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? '周' : '') + week[time.getDay() + ''])
	}
	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((
			'00' + o[k]).substr(('' + o[k]).length)))
	}
	return fmt
}

//修改日期格式结构
function OnDate(data) {
	let list = data
	list.forEach(item => {
		var dateArray = item.date.split("-");
		var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
		item.getDay = "周" + "日一二三四五六".charAt(date.getDay());
		item.get = "7123456".charAt(date.getDay());
		item.getDate = new Date(item.date).getDate()
	})
	return list
}

//算年龄
function Onage(data) {
	// var birthday = data;
	// var birthday_time = birthday.split("-");
	// var birthYear = birthday_time[0];
	// var d = new Date();
	// var nowYear = d.getFullYear();
	// var age = nowYear - birthYear;
	// return age
	
	var age = '';
	try{
		var birthday = data;
		var birthday_time = birthday.split("-");
		var y1 = birthday_time[0];
		var m1 = birthday_time[1];
		var d1 = birthday_time[2];
		var now = new Date();
		var y2 = now.getFullYear();
		var m2 = now.getMonth() + 1;
		var d2 = now.getDate();
		
		age = y2 - y1;
		if (parseInt(m2+''+d2) < parseInt(m1+''+d1)) age -= 1;
	}catch(e){
		age = '--';
	}
	
	return age;
}

/**
 * dateTimeStamp是评论的发送时间   2020-01-12 20:10:15 这样的形式
 * @param dateTimeStamp
 * @returns {string}
*/
function timeAgo(dateTimeStamp) {
	let result = "";
	let minute = 1000 * 60;      //把分，时，天，周，半个月，一个月用毫秒表示
	let hour = minute * 60;
	let day = hour * 24;
	let week = day * 7;
	let halfamonth = day * 15;
	let month = day * 30;
	let now = new Date().getTime();   //获取当前时间毫秒

	dateTimeStamp = dateTimeStamp.substring(0, 18);
	//必须把日期'-'转为'/'
	dateTimeStamp = dateTimeStamp.replace(/-/g, '/');
	let timestamp = new Date(dateTimeStamp).getTime();

	let diffValue = now - timestamp;//时间差

	if (diffValue < 0) {
	  return result;
	}
	let minC = diffValue / minute;  //计算时间差的分，时，天，周，月
	let hourC = diffValue / hour;
	let dayC = diffValue / day;
	let weekC = diffValue / week;
	let monthC = diffValue / month;
	if (monthC >= 1 && monthC <= 3) {
		result = " " + parseInt(monthC) + "月前"
	} else if (weekC >= 1 && weekC <= 3) {
		result = " " + parseInt(weekC) + "周前"
	} else if (dayC >= 1 && dayC <= 6) {
		result = " " + parseInt(dayC) + "天前"
	} else if (hourC >= 1 && hourC <= 23) {
		result = " " + parseInt(hourC) + "小时前"
	} else if (minC >= 1 && minC <= 59) {
		result = " " + parseInt(minC) + "分钟前"
	} else if (diffValue >= 0 && diffValue <= minute) {
		result = "刚刚"
	} else {
		let datetime = new Date();
		datetime.setTime(dateTimeStamp);
		let Nyear = datetime.getFullYear();
		let Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
		let Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
		let Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
		let Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
		let Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
		result = Nyear + "-" + Nmonth + "-" + Ndate
	}
	return result;
}

/** ------ im ------ */
// 数组置顶
function __toFirst(arr,index){
	if (index != 0) {
		arr.unshift(arr.splice(index,1)[0]);
	}
	return arr;
}
function __formatTime(timestamp, nhm){ //nhm：不需要时分
	var newDate = new Date(parseInt(timestamp) * 1000)

	var year = newDate.getFullYear(); //得到年份
	var month = newDate.getMonth() + 1; //得到月份
	var date = newDate.getDate(); //得到日期
	var day = newDate.getDay(); //得到周几
	var hour = newDate.getHours(); //得到小时
	var minutes = newDate.getMinutes(); //得到分钟
	var sec = newDate.getSeconds(); //得到秒
	var MS = newDate.getMilliseconds(); //获取毫秒

	var thisDate = new Date();
	var thisyear = thisDate.getFullYear(); //获取当前年份
	var thismonth = thisDate.getMonth() + 1; //获取当前月份
	var thisdate = thisDate.getDate(); //获取当前日期

	const JUST_NOW = 3000; //3s内
	const IN_SECOND = 1000 * 60; //一分钟
	const IN_MINUTE = 1000 * 60 * 60; //一小时
	const IN_HOUR = 1000 * 60 * 60 * 12; //12小时
	const IN_DAY = 1000 * 60 * 60 * 24 * 1; //1天
	const IN_WEEK = 1000 * 60 * 60 * 24 * 7; //1周
	const IN_MONTH = 1000 * 60 * 60 * 24 * 30; //1个月
	const arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");

	var ymd = year + (nhm?'/':'年') + (month>=10?month:'0'+month)+(nhm?'/':'年') + (date>=10?date:'0'+date) //年月日
	var week = arr_week[day] //周
	var hm = (hour>=10?hour:'0'+hour) + ":" + (minutes>=10?minutes:'0'+minutes) //时分

	var diff = parseInt(((new Date(thisyear+'/'+thismonth+'/'+thisdate)).getTime()-(new Date(year+'/'+month+'/'+date)).getTime())/IN_DAY); //相差天数

	var dateStr = "";
	switch(diff){
		case 0: //今天
			return hm;
			break;
		case 1:
			dateStr = '昨天';
			break;
		case 2:
			dateStr = '前天';
			break;
		case 3:
		case 4:
		case 5:
		case 6:
			dateStr = week;
			break;
		default:
			dateStr = ymd
			break;
	}

	return dateStr+(nhm?'':' '+hm)
}
function __formatChat(message){
	var str = "";
	try{
		var fromType = message.fromType || 'user'
		if(fromType=='user'){
			switch(message.type){
				case 'textCard': //文字卡片
					str = "";
					for(var i in message.content.list){
						str += message.content.list[i].name+" "+message.content.list[i].value;
					}
				break;
				case 'img': //图片
					str = "[图片]";
				break;
				case 'imgs': //图片
					str = "";
					for(var i in message.content.list){
						str += "[图片] ";
					}
				break;
				case 'text': //文本
					str = "<div style='overflow:hidden;white-space:nowrap;text-overflow:ellipsis;'>"+message.content.text/*.replace(/\<img/g,'<img style="width:20px;height:20px;"')*/+"</div>";
				break;
				case 'voice': //语音
					str = "[语音]";
				break;
				case 'file': //图片
					str = "[文件]";
				break;
				case 'dzcf': //处方
					str = "[处方] ";
					for(var i in message.content.list){
						str += message.content.list[i].name+" "+message.content.list[i].value;
					}
				break;

				default:
					str = "...";
				break;
			}
		}
	} catch(e) {
        console.log('error: ' + e)
        str = 'error: ' + e
    }

    return str
}
/** ------ im end ------ */

function img(img_path, params, _http_imgFull) {
	var path = "";
	var http_imgFull = _http_imgFull || 'https://health.vipmed.cn/'
	
	if (
			img_path != undefined
			&& img_path != ""
			&& img_path != null
			&& img_path != 'null'
			&& img_path != 'NULL'
		) {
		if (img_path.indexOf("http://") == -1 && img_path.indexOf("https://") == -1) {
			path = http_imgFull + img_path;
		} else {
			path = img_path;
		}
	}else{
		path = params || ''
	}
	return path;
}
function cdn(img_path, params) {
	return img(img_path, params, 'http://cdn.yingpaipay.com')
}

function timestampFormat( timestamp ) {
    var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
    var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数
 
    var curDate = new Date( curTimestamp * 1000 ); // 当前时间日期对象
    var tmDate = new Date( timestamp * 1000 );  // 参数时间戳转换成的日期对象
 
    var Y = tmDate.getFullYear(), m = tmDate.getMonth() + 1, d = tmDate.getDate();
    var H = tmDate.getHours(), i = tmDate.getMinutes(), s = tmDate.getSeconds();
 
    if ( timestampDiff < 60 ) { // 一分钟以内
        return "刚刚";
    } else if( timestampDiff < 60*60 ) { // 一小时前之内
        return Math.floor( timestampDiff / 60 ) + "分钟前";
    } else if ( curDate.getFullYear() == Y && curDate.getMonth()+1 == m && curDate.getDate() == d ) {
        return '今天' + zeroize(H) + ':' + zeroize(i);
    } else {
        var newDate = new Date( (curTimestamp - 24*60*60) * 1000 ); // 参数中的时间戳加一天转换成的日期对象
        if ( newDate.getFullYear() == Y && newDate.getMonth()+1 == m && newDate.getDate() == d ) {
            return '昨天' + zeroize(H) + ':' + zeroize(i);
        } else if ( curDate.getFullYear() == Y ) {
            return  zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
        } else {
            return  Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
        }
    }
}
function zeroize( num ) {
	return (String(num).length == 1 ? '0' : '') + num;
}

const getUrlParams = function(param, k, p) {
	if (typeof param != 'string') return {};
	k = k ? k : '&'; //整体参数分隔符
	p = p ? p : '='; //单个参数分隔符
	var value = {};
	if (param.indexOf(k) !== -1) {
		param = param.split(k);
		for (var val in param) {
			if (param[val].indexOf(p) !== -1) {
				var item = param[val].split(p);
				value[item[0]] = item[1];
			}
		}
	} else if (param.indexOf(p) !== -1) {
		var item = param.split(p);
		value[item[0]] = item[1];
	} else {
		return param;
	}
	return value;
}
 
/** 
 *判断成人和儿童 
 */
const isChildren = function(idCard) {
	var birthDayDate = parseInt(idCard.substring(6,14));
	
	var myDate = new Date(),
	year = myDate.getFullYear() - 12,
	month = myDate.getMonth()+1,
	day = myDate.getDate();
	
	if(birthDayDate>=parseInt(year+''+(month<10?'0'+month:month)+''+(day<10?'0'+day:day))){
		return true
	}
	return false
}

module.exports = {
	checkMobile,
	checkCard,
	formatTime,
	OnDate,
	Onage,
	timeAgo,
	/** ------ im ------ */
	__toFirst,
	__formatTime,
	__formatChat,
	/** ------ im end ------ */
	
	cdn,
	img,
	timestampFormat,
	
	getUrlParams,
	isChildren,
}
